// index.js
const { api } = require("../../utils/api.js");

Page({
  data: {
    isLoading: false,
    sessionId: "",
    userInfo: null,
    isNetworkConnecting: false, // 网络连接中状态
    loadingText: "", // 加载文字提示
    networkStatus: true, // 网络状态
    startTime: 0, // 请求开始时间
  },

  // 添加标志位防止重复请求
  isRequestingCode: false,

  onLoad() {
    // 监听网络状态变化
    wx.onNetworkStatusChange((res) => {
      this.setData({ networkStatus: res.isConnected });
      if (res.isConnected && !this.data.sessionId) {
        this.checkLoginStatus();
      }
    });

    // 检查网络状态
    wx.getNetworkType({
      success: (res) => {
        const isConnected = res.networkType !== "none";
        this.setData({ networkStatus: isConnected });
        if (isConnected) {
          this.checkLoginStatus();
        }
      },
    });
  },

  onShow() {
    // 只在有网络且没有sessionId时尝试登录
    if (this.data.networkStatus && !this.data.sessionId) {
      this.checkLoginStatus();
    }
  },

  // 检查登录状态的统一处理
  checkLoginStatus() {
    const token = wx.getStorageSync("token");
    if (!token) {
      // 模拟登录不需要sessionId，直接设置一个临时值
      this.setData({ sessionId: `temp_${Date.now()}` });
    } else {
      // 已登录，避免闪屏
      setTimeout(() => {
        wx.switchTab({ url: "/pages/home/index" });
      }, 100);
    }
  },

  //获取用户信息（模拟登录）
  // getUserInfo() {
  //   const that = this;

  //   this.setData({
  //     isLoading: true,
  //     loadingText: "登录中...",
  //   });

  //   // 模拟登录延迟
  //   setTimeout(() => {
  //     // 模拟用户数据
  //     const mockUserData = {
  //       openId: `user_${Date.now()}`,
  //       token: `token_${Date.now()}`,
  //       nickName: "测试用户",
  //       avatarUrl: "http://117.50.47.34:9000/icon/logo.png",
  //       gender: 1,
  //       country: "China",
  //       province: "广东",
  //       city: "深圳",
  //     };

  //     // 保存用户信息
  //     that.setData({
  //       userInfo: mockUserData,
  //       isLoading: false,
  //     });
  //     wx.setStorageSync("token", mockUserData.token);
  //     wx.setStorageSync("userInfo", mockUserData);

  //     // 显示成功提示并跳转
  //     that.showToast("登录成功", "success", () => {
  //       wx.switchTab({ url: "/pages/home/index" });
  //     });
  //   }, 1500);
  // },

  // 统一处理提示
  showToast(message, icon = "none", callback) {
    wx.showToast({
      title: message,
      icon: icon,
      duration: icon === "success" ? 1500 : 2000,
      success: () => {
        if (callback && icon === "success") {
          setTimeout(callback, 1500);
        }
      },
    });
  },

  // 获取登录code并换取sessionId
  getLoginCode() {
    if (this.isRequestingCode) return;

    const that = this;
    this.isRequestingCode = true;

    // 显示连接中状态
    this.setData({
      isNetworkConnecting: true,
      startTime: Date.now(),
    });

    wx.login({
      success(res) {
        if (!res.code) {
          that.setData({ isNetworkConnecting: false });
          console.error("wx.login 返回的 code 为空");
          return;
        }

        console.log("获取到登录code:", res.code); // 添加日志

        // 确保加载动画至少显示800ms，体验更流畅
        const minLoadingTime = 800;
        const elapsed = Date.now() - that.data.startTime;
        const remainingTime = Math.max(0, minLoadingTime - elapsed);

        setTimeout(() => {
          api
            .getSessionId(res.code)
            .then((response) => {
              console.log("getSessionId 返回数据:", response); // 添加日志
              that.setData({ isNetworkConnecting: false });

              if (response && response.code === 200) {
                // 即使 data 为 null 也认为是成功的
                const sessionId =
                  response.data?.sessionId || `temp_${Date.now()}`;
                that.setData({ sessionId });
                wx.setStorageSync("sessionId", sessionId);

                // 检查是否有保存的登录信息
                const savedUserInfo = wx.getStorageSync("userInfo");
                const token = wx.getStorageSync("token");
                if (savedUserInfo && token) {
                  that.validateToken(token);
                }

                // 保存用户信息到本地存储，供订单系统使用
                wx.setStorageSync('userInfo', {
                  userId: response.data.userId,
                  nickName: response.data.nickName,
                  avatarUrl: response.data.avatarUrl
                });
              } else {
                console.error("getSessionId 返回异常:", response); // 添加日志
                that.showToast(response?.msg || "获取登录凭证失败");
              }
            })
            .catch((error) => {
              console.error("获取sessionId失败，详细错误:", error); // 修改错误日志
              that.setData({ isNetworkConnecting: false });
              that.showToast("网络连接失败，请重试");
            });
        }, remainingTime);
      },
      fail(error) {
        console.error("wx.login 失败:", error); // 添加日志
        that.setData({ isNetworkConnecting: false });
        that.showToast("登录失败，请重试");
      },
      complete() {
        that.isRequestingCode = false;
      },
    });
  },

  // 验证token是否有效
  validateToken(token) {
    // 此处可调用API验证token有效性
    // 如果有效，直接跳转首页
    // 如果无效，清除token
  },

  // 获取用户信息
  getUserInfo() {
    const that = this;
    
    // 先获取用户信息
    wx.getUserProfile({
      desc: '用于完善用户资料',
      success: (res) => {
        console.log('获取用户信息成功:', res);
        
        this.setData({
          isLoading: true,
          loadingText: "登录中...",
        });

        const sessionId = this.data.sessionId || wx.getStorageSync("sessionId");

        if (!sessionId) {
          this.showToast("登录状态异常，请重试");
          this.getLoginCode();
          return this.setData({ isLoading: false });
        }

        // 添加最小loading时间保证体验流畅
        const startTime = Date.now();
        const minLoadingTime = 1000;

        api
          .login({
            userInfo: res.userInfo
          })
          .then((res) => {
            console.log("登录接口返回数据:", res);
            const elapsed = Date.now() - startTime;
            const remainingTime = Math.max(0, minLoadingTime - elapsed);

            setTimeout(() => {
              if (res.code === 200 && res.data?.wechatUserDto?.token) {
                const userData = res.data.wechatUserDto;
                console.log("用户数据:", userData);
                this.setData({ userInfo: userData });
                wx.setStorageSync("token", userData.token);
                wx.setStorageSync("userInfo", userData);

                this.showToast("登录成功", "success", () => {
                  wx.switchTab({ url: "/pages/home/index" });
                });
              } else {
                this.showToast(res.msg || "登录失败");
              }
              this.setData({ isLoading: false });
            }, remainingTime);
          })
          .catch((error) => {
            console.error("登录失败:", error);
            const elapsed = Date.now() - startTime;
            const remainingTime = Math.max(0, minLoadingTime - elapsed);

            setTimeout(() => {
              this.showToast(error.message || "网络连接失败");
              this.setData({ isLoading: false });
            }, remainingTime);
          });
      },
      fail: (err) => {
        console.error('获取用户信息失败:', err);
        this.showToast("需要授权用户信息才能登录");
      }
    });
  },

  // 获取sessionId失败，显示按钮重试
  getSessionIdFailed() {
    this.getLoginCode();
  },

  // 显示用户协议
  showAgreement() {
    wx.navigateTo({
      url: "/pages/agreement/index",
    });
  },

  // 显示隐私政策
  showPrivacy() {
    wx.navigateTo({
      url: "/pages/privacy/index",
    });
  },
});
